#include "CObjectManager.h"
#include "CGamePlayState.h"
#include "CGameClass.h"
#include "CPlayer.h"
#include "CPlayerIdleState.h"
#include "CSunshine.h"

void CObjectManager::Add(CBase *pBase)
{
	pBase->AddRef();
	m_vObjects.push_back(pBase);
}

void CObjectManager::Remove(CBase *pBase)
{
	for (unsigned int i = 0; i < m_vObjects.size(); i++)
	{
		if (m_vObjects[i] == pBase)
		{
			pBase->Release();
			m_vObjects.erase(m_vObjects.begin() + i);
			break;
		}
	}
}

void CObjectManager::Clear()
{
	for (unsigned int i = 0; i < m_vObjects.size(); i++)
		m_vObjects[i]->Release();

	m_vObjects.clear();
}

void CObjectManager::CheckCollisions()
{
	for (unsigned int i = 0; i < m_vObjects.size(); i++)
	{
		if(m_vObjects[i]->m_unType == CLOUD)
		{

			for(int k = 0; k < m_vObjects.size(); ++k)
				if(m_vObjects[k]->m_unType == NOODLE)
					m_vObjects[i]->CheckCollision(m_vObjects[k]);
		}

		for (unsigned int j = i + 1; j < m_vObjects.size(); j++)
		{
			

			if(m_vObjects[i]->m_unType == PLAYER || m_vObjects[i]->m_unType == CLOUD || m_vObjects[i]->m_unType == PICK_UP)
			{
				if(m_vObjects[i]->m_unType == PLAYER && m_vObjects[i]->CheckCollision(m_vObjects[j]))
				{
					if(((CPlayer*)m_vObjects[i])->m_bFalling)
						((CPlayer*)m_vObjects[i])->ChangeState(CPlayerIdleState::GetInstance());
				}
				else
					m_vObjects[i]->CheckCollision(m_vObjects[j]);
			}
		}
	}
}

void CObjectManager::UpdateAll(float fElapsed)
{
	for (unsigned int i = 0; i < m_vObjects.size(); i++)
	{
		if(m_vObjects[i]->m_unType == PICK_UP && ((CSunshine*)m_vObjects[i])->m_bAlive == false)
		{
			m_vObjects.erase(m_vObjects.begin()+i);
		}
		else
			m_vObjects[i]->Update(fElapsed);
	}
}

#define RENDER_CULLING_OFFSET 20.0f

void CObjectManager::RenderAll()
{
	for (unsigned int i = 0; i < m_vObjects.size(); i++)
	{
		//Mat4 mModelMatrix;
		//mModelMatrix.MakeTranslate(m_vObjects[i]->m_Pos);

		//Mat4 mViewMatrix(CGamePlayState::GetInstance()->GetCamera()->GetViewMatrix(true));
		//Mat4 mProjection(CGamePlayState::GetInstance()->GetCamera()->GetProjectionMatrix());

		//Mat4 mScreenSpaceMatrix = mModelMatrix * mViewMatrix * mProjection;
		//float fObjectSSXCoord = mScreenSpaceMatrix.wx * (float)CGameClass::GetInstance()->GetScreenWidth();
		//float fObjectSSYCoord = mScreenSpaceMatrix.wy * (float)CGameClass::GetInstance()->GetScreenHeight();

		//if((fObjectSSXCoord >= -RENDER_CULLING_OFFSET && fObjectSSXCoord <= (float)CGameClass::GetInstance()->GetScreenWidth() + RENDER_CULLING_OFFSET && 
		//	fObjectSSYCoord >= -RENDER_CULLING_OFFSET && fObjectSSYCoord <= (float)CGameClass::GetInstance()->GetScreenHeight() + RENDER_CULLING_OFFSET) || 
		//	m_vObjects[i]->m_unType == WORLD)
		
		m_vObjects[i]->Render();
	}
}

void CObjectManager::OnResetDevice(void)
{

}

void CObjectManager::OnLostDevice(void)
{

}